Repository navigation
feat(api): generate the frontend API contract with Kubb - #3
Merged
Merged
Conversation
Fast refresh only works when a file exports only components. Move the cva variants, hooks, contexts, and the Notification API to their own files next to the components, and update the imports. The public names do not change.
The filter-demo route imported types inline with values. With verbatimModuleSyntax the route split left a side-effect import of the filter builder in the route file, so the filter builder, the calendar, and react-aria went into the entry chunk. Import the types with import type. Also put the vendor libraries that the root layout always loads (react, the router, the query client, motion) in their own chunks. The entry chunk goes from 897 kB to 288 kB, and the build has no chunk size warning.
The project rules forbid barrel files. The filter-builder barrel also caused the large entry chunk: an import of it from the filter demo route pulled the whole filter builder into the entry. The route now imports from each source file.
The project rules forbid barrel files, and nothing imported this one.
The three theme buttons were wider than the icon rail, so the rail clipped them. The buttons now stack vertically in the rail.
The variants use the destructive color for text, but the dark value was too dark to read on the dark background. The dark value is now the current shadcn value.
No file imports the useComboboxFilter hook. Remove the file.
pdevito3
force-pushed
the
feat/kubb-contracts
branch
from
October 18, 2026 16:07
e13e230 to
5ba98f3
Compare
Remove the old filter hook comments in the autocomplete and combobox files. Rename notifications.tsx to toaster.tsx, because the file holds the Toaster.
The name Notifications was too close to the Notification API that shows a toast. The JSDoc now says that the component is the container, and that Notification shows a toast.
A Debug build of the Server writes the OpenAPI document to FullstackTemplate.Server/openapi/. Kubb generates one client, type, and Zod file for each endpoint in frontend/src/api/generated/. The weather hooks use the generated clients. A CI workflow fails when the committed contract is not current. See docs/adr/0001-commit-generated-api-contract.md.
GetDocument.Insider starts the host to read the endpoints, so each hosted service ran during a Debug build. With a connection string in the environment, the build applied migrations to that database, or failed with ObjectDisposedException when the database was not available. The build-time run now removes all hosted services.
A global Produces("application/json") filter was added only so that each
operation in the OpenAPI document had one media type. The filter also
changed the responses at run time: a 400 for malformed JSON and a
NotFound() from a controller had the content type application/json
instead of application/problem+json. Only the errors from the exception
handler still sent problem+json, and the document listed each
ProblemDetails response as application/json.
Remove the filter, so MVC sends ProblemDetails as application/problem+json
again. Add JsonContentTypeTransformer, which keeps one media type for each
response in the document: application/problem+json for a response that
returns ProblemDetails, and application/json for the other responses.
Add functional tests for malformed JSON and for NotFound().
The generated Kubb files do not change, because Kubb reads both media
types as JSON.
Strict number handling (for MVC and for minimal APIs) and a JSON input formatter limited to application/json were added only to change the OpenAPI document: to type numbers as integer instead of integer or string, and to remove the text/json and application/*+json request body types. They also changed the runtime behavior: a text/json body got 415, and a number sent as a string got 400. Restore the ASP.NET defaults in AddControllers. Add RemoveStringFromNumbersTransformer, which removes the string type and its pattern from number and integer schemas, and make JsonContentTypeTransformer keep only application/json for request bodies. The Server accepts the lenient forms again, but the contract states only the canonical form. The OpenAPI document and the generated Kubb files do not change. Add a functional test for a text/json body.
A list client returns the full response only because its operationId ends in "List". Nothing checked that rule, so a renamed list endpoint got a client that silently dropped the X-Pagination header. Callers also had to read and JSON.parse the header by hand, and no test checked the shape of the header. - Add RequireListOperationNameTransformer. The OpenAPI build now fails when an operation documents the X-Pagination header but its name does not end in "List", or when its name ends in "List" but it has no such header. The message names the endpoint and tells how to fix it. - Add parsePagination in frontend/src/lib/pagination.ts. It reads the header from the full result of a list client and returns the generated PaginationMetadata type. - Add a functional test that calls the user list endpoint and checks the property names and value types of the X-Pagination header. - Document the naming rule and the helper.
The package was on 10.0.1. Version 10.0.13 is the newest patch of the .NET 10 release. Main already updates Microsoft.OpenApi to 2.12.2.
…crosoft.AspNetCore.OpenApi Both packages come from the same ASP.NET Core release, so they now use the same version, 10.0.13. The OpenAPI document does not change.
Extract the X-Pagination assertion into a helper and use it for the user list and the tenant list. The tenant list is not tenant scoped, so the test filters on a unique name.
A 400 comes from model binding or model validation, and the Server sends a ValidationProblemDetails body with the errors field. The controllers now declare that type, so the OpenAPI document and the generated contract state the real shape. The controller rule and the backend doc say to do the same for new controllers.
Both jobs restore the NuGet package folder with actions/cache. The key uses the OS and the hash of the package and project files. The checkout steps do not keep the token in the git config. The test job does not write the OpenAPI document again, because the api-contract job checks it.
A Debug build of the Server writes the OpenAPI document. GitHub now collapses it in pull request diffs, as it does for the Kubb output.
Only a Debug build writes the document, so only a Debug build fails on a bad endpoint name. The build-time run does no OIDC discovery. Thus the committed file has no OAuth2 security scheme. The runtime document has it.
The frontend had no unit test runner. Add Vitest and a test script. Vitest uses vite.config.ts, so the @/ alias works. The tests cover a valid header, a header in a different case, a missing header, and a header that is not JSON.
…tConfig alias The alias added no fields after the suppressErrorToast option moved into the axios module augmentation.
With throwOnError false, axios accepts all statuses. The apiClient error interceptor does not run, so there is no toast and no ProblemDetailsError. Describe this mode next to the default mode.
The ui variants are in *-variants.ts files and the hooks are in use-*.ts files. A component from shadcn add imports them from the component file. Tell the reader to change that import.
A header name is case-insensitive. parsePagination did a property lookup, so headers that a test builds with a mixed-case name gave an error. The lookup now ignores the case.
The composite index (tenant_id, last_name, first_name, id) matches the tenant filter and the default sort of GetUserList. It replaces the index on tenant_id alone, because TenantId is the first column.
pdevito3
force-pushed
the
feat/kubb-contracts
branch
from
October 18, 2026 18:32
5ba98f3 to
9489837
Compare
A page number less than 1 gave a negative OFFSET, and a negative page size gave a negative LIMIT. PostgreSQL rejected both, so the request got a 500. A page size of 0 gave a 200 with totalPages 2147483647 and hasNext true. The contract now states a minimum of 1 for both values.
AddTenant and UpdateTenant now check for the name before the save and throw a ConflictException on name. Before, the unique index stopped the save, and the 409 had an empty errors object, so a form could not show the error on the name field. The update check does not count the tenant itself.
…ermission errors AddUser gave the key TenantId, and Permission gave the key Permission. The keys are now tenantId and permission, the same as the role, email, and identifier keys.
Only the BFF has CORS, and the browser calls the BFF on the same origin as the SPA, so the Access-Control-Expose-Headers entry had no effect. The filter tests now check the page data in the header, and that a result that is not a paged list gets no header.
…st name, then first name
The comment said that a request without a version gets the default version. The version is in the URL path, and the branch removed AssumeDefaultVersionWhenUnspecified, so no request is without a version.
…roup the imports
The JSDoc of apiClient used /api/weather and post(url, { body }), and both were wrong. The example now calls a generated client, and uses apiClient directly only for /bff/user. The imports of api-client.ts and the weather hooks now obey the external, internal, relative grouping.
…e for parsePagination
…ted again The build and the generate step do not delete the document or the generated folder of a removed API version. CI now deletes the committed files first, so a stale file shows in the diff as a deleted file. docs/backend.md now gives the steps to remove a version.
The docs named only src/api/generated/. Each API version after v1 has its own folder, for example src/api/generated-v2/, and the rule to not edit applies to each folder.
…ns of a user works On 1.16.0, `Permissions ^$ "x"` returned 400 and `Permissions == "x"` returned 500, because QueryKit did not treat an IReadOnlyList<string> as a collection (pdevito3/QueryKit#201).
Resolve the conflicts with the change to prefixed string IDs: - Keep the typed 400 and 422 responses with the string id parameters. - Keep the route names of main, and add GetByIdentifier. - Expect the key tenantId in the tenant ID test of main. - Set the IDs of the default sort test through the creation model. - Move the filter conversion case to the permission count of the user list, because the tenant DTO has only string fields now. - Generate the contract again. The IDs are strings, not uuids.
A bad sort direction threw QueryKitParsingException, so its error had the key filters. An operator that does not fit the property type, for example ^^ on a string, threw an ArgumentException and gave 500. ApplyFilters and ApplySortOrder now wrap the QueryKit calls. They throw a QueryInputException with the name of the parameter. A listed QueryKit input error keeps its message. A .NET exception gets a fixed message, because its message names .NET types, and the trace gets the exception.
A domain guard took no field, so the problem had an empty errors object. Each guard now takes the name of the request field. InitiateUserAndTenant checks for a taken tenant name and returns a 409 with the key tenantName. A blank tenant name has the key tenantName too. The 409 for a unique index now names the field of the index. A unit test makes sure that each unique index in the model has a field.
…kend-feature skill
A large pageNumber wrapped the offset to a negative value, and the list returned 500. pageNumber now has a maximum of int.MaxValue / 500, so the list returns 400 with the key pageNumber. PagedList uses checked math as a second guard.
Five users with the same role, read one for each page, each show on exactly one page, in Id order. The test fails when the tie-break on Id is deleted. A tenant test cannot fail, because the tenant names are unique.
CI used pnpm 9, which runs the install script of each package. pnpm 10 runs only the scripts of onlyBuiltDependencies. CI and the BFF Dockerfile now take the pnpm version from packageManager in frontend/package.json.
# Conflicts: # frontend/src/lib/api-client.ts # frontend/src/main.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Generates the frontend API contract with Kubb, with one file for each endpoint.
Merge #5 first. This branch has the commits of #5, and they drop out of this diff after the merge.
Changes
frontend/src/api/generated/. Each OpenAPI document gets its own folder:generatedfor v1,generated-v2for v2, and more.apiClient, so they get the CSRF header, the cookies, and the error toasts.api-contractjob of theCIworkflow deletes them, generates them again, and fails when they are not current. A document of a removed API version also fails the job.Idafter each sort, so a row cannot show on two pages. A composite index serves the default sort of the user list.PagedList.CreateAsynccounts the rows asynchronously.PagedListuses checked math for the page offset.ApplyFiltersandApplySortOrderwrap QueryKit. They throw aQueryInputExceptionwith the name of the parameter that failed.errors.packageManager. CI and the BFF Dockerfile use this version. Onlyesbuildcan run an install script.Behavior changes
Update the API clients outside this repo for these changes:
filtersandsortOrderapply to the DTO fields only. A field that the DTO does not show, for exampleCreatedBy, gives 400.filtersorsortOrdervalue that QueryKit cannot apply gives 400, not 500. The key inerrorsis the parameter that failed, for examplesortOrderforName foo. An operator that does not fit the property type, for exampleName ^^ "x", gives 400 with the fixed message "The filters value is not valid.".errorsfield are the request field names in camelCase. For example:email,firstName,role,permission, andtenantId. A blank tenant name on initiate usestenantName.filters,sortOrder,pageNumber, andpageSize.identifier. A duplicate tenant name gives the keyname, ortenantNameon initiate. Initiate now checks the tenant name before the save.pageNumberor apageSizeless than 1 gives 400. ApageNumbermore than 4294967 gives 400, not 500.application/problem+json..github/workflows/ci.yml, with the nameCI. Update each required status check that uses the old name.Tests
DomainProblemDetailsmaps: 400, 404, 409, 422, and 500. A unit test fails if a unique index in the model has no request field.Permissionsincluded), and theX-Paginationheader.Idis deleted. A tenant test cannot fail this way, because the tenant names are unique.parsePagination,problem-details, and theapiClientinterceptor through a generated client.Known limits
Permissionsgives 500, because EF cannot translate a sort on a list (A sort on a collection property must throw SortParsingException QueryKit#205). QueryKit 1.16.1 fixed the filter on this field (Collection filters fail on IReadOnlyList<T>, HashSet<T>, arrays, and on == against a direct collection property QueryKit#201), but not the sort.^^on a scalar throws a .NETArgumentExceptionin QueryKit (The ^^ operator on a scalar property throws ArgumentException, not a parsing exception QueryKit#204). The wrapper maps it to 400.